<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Tree;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Menu;
use plugin\admin\app\model\Role;
use plugin\admin\app\model\Rule;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;

/**
 * 菜单
 */
class MenuController extends Crud
{
    /**
     * 不需要权限的方法
     *
     * @var string[]
     */
    protected $noNeedAuth = ['get', 'permission'];

    /**
     * @var Rule
     */
    protected $model = null;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new Menu();
    }

    //顶部菜单
    public function top_menu(){
        return json(['data'=>[]]);
    }

    //菜单
    public function menu(Request $request){
        return $this->getTreeData($request);
    }


    //菜单
    public function getChild(Request $request){
        $pid = $request->post('pid','0');
        $data = Menu::where(['pid'=>$pid])->orderBy('sort','DESC')->get();
        return json(['data'=>$data]);
    }

    //树形菜单
    public function getTreeData(Request $request){

        $items = Menu::orderBy('sort', 'desc')->get()->toArray();

        $formatted_items = [];
        foreach ($items as $item) {
            $item['pid'] = (int)$item['pid'];
            $item['label'] = $item['label'];
            $item['value'] = $item['id'];
            $formatted_items[] = $item;
        }

        $tree = new Tree($formatted_items);
        $tree_items = $tree->getTree();
        return json(['data'=>$tree_items]);
    }




}
